<?php
namespace wechat;
use think\Controller;
use SimpleXMLElement;

// 微信接入
class Config extends Controller {
	
	/**
	* 微信推送过来的数据或响应数据 2017-10-15
	*/
	private $data = array();

	/**
	* 构造方法，用于实例化微信SDK 2017-10-15
	*/
	public function __construct($token,$attach = array()){
		if(request() -> isGet()){
			//!isset($attach['uid']) && $attach['uid'] = 0;		
			//apilog($attach['uid'],'wechat','wechataccess','',input('param.'),'');
			$this -> auth($token) || die('token信息错误');
			exit(input('get.echostr'));
		}else{
			!isset($attach['uid']) && $attach['uid'] = 0;
			//apilog($attach['uid'],'wechat','wechatpush','',input('param.'),'');
			
			$this -> auth($token) || die('token信息错误');
			$xml = file_get_contents("php://input");
			apilog($attach['uid'], 'wechat', 'getrequestxml', '', $xml, '');
			$xml || exit;
			$this -> data = xmltoarray($xml);
		}
	}
	
	/**
	* 获取微信推送的数据	转换为数组后的数据 2017-10-15
	*/
	public function request($attach = array()){
		!isset($attach['uid']) && $attach['uid'] = 0;
		apilog($attach['uid'], 'wechat', 'getrequestarray', '', $this->data, '');
       	return $this -> data;
	}

	/**
	* 响应微信发送的信息（自动回复）2017-10-15
	*/
	public function response($content, $type = 'text', $flag = 0, $attach = array('uid'=>2)){		
		$this->data = array(
			'ToUserName'   => $this -> data['FromUserName'],
			'FromUserName' => $this -> data['ToUserName'],
			'CreateTime'   => time(),
			'MsgType'      => $type,
		);

		//判断成员方法是不是存在
		if(!method_exists($this, $type)){
		    return false;
		}
		/* 添加类型数据 */
		$this -> $type($content);
		
		/* 转换数据为XML */
		$xml = new SimpleXMLElement('<xml></xml>');
		$this -> data2xml($xml, $this->data);
		apilog($attach['uid'], 'wechat', 'response', '', $this->data, $xml->asXML());
		exit($xml->asXML());
	}
	
	/**
	* 接入多客服 	2017-10-15
	*/
	private function transfer_customer_service($content){
		$TransInfo['KfAccount'] = $content;
		$this -> data['TransInfo'] = $TransInfo;
	}

	/**
	* 回复文本信息 	2017-10-15
	*/
	private function text($content){
		$this->data['Content'] = $content;
	}
	
	/**
	* 回复图片信息	2017-03-10
	*/
	private function image($content){
		$this->data['Image'] = array('MediaId'=>$content);
	}
	
	/**
	* 回复语音信息	2017-03-10
	*/
	private function voice($content){
		$this->data['Voice'] = array('MediaId'=>$content);
	}
	
	/**
	* 回复视频信息	2017-03-10
	*/
	private function video($content){
		list(
			$content['MediaId'],
			$content['Title'],
			$content['Description'],
		) = $content;
		$this->data['Video'] = $content;
	}

	/**
	* 回复音乐信息	2017-03-10
	*/
	private function music($content){
		list(
			$content['Title'], 
			$content['Description'], 
			$content['MusicUrl'], 
			$content['HQMusicUrl']
		) = $content;
		$this->data['Music'] = $content;
	}

	/**
	* 回复图文信息
	*/
	private function news($news){
		$articles = array();
		$i = 0;
		foreach($news as $value){
			$articles[$i]['Title'] = $value['title'];
			$articles[$i]['Description'] = $value['description'];		
			$articles[$i]['PicUrl'] = $value['picurl'];
			$articles[$i]['Url'] = $value['url'];
			$i++;
			if($i >= 9) { break; } //最多只允许10调新闻
		}
		
		$this->data['ArticleCount'] = count($articles);
		$this->data['Articles'] = $articles;
	}

	/**
    * 数据XML编码
    */
    private function data2xml($xml, $data, $item = 'item') {
        foreach ($data as $key => $value) {
            /* 指定默认的数字key */
            is_numeric($key) && $key = $item;

            /* 添加子元素 */
            if(is_array($value) || is_object($value)){
                $child = $xml->addChild($key);
                $this->data2xml($child, $value, $item);
            } else {
            	if(is_numeric($value)){
            		$child = $xml->addChild($key, $value);
            	} else {
            		$child = $xml->addChild($key);
	                $node  = dom_import_simplexml($child);
				    $node->appendChild($node->ownerDocument->createCDATASection($value));
            	}
            }
        }
    }

    /**
	* 对数据进行签名认证，确保是微信发送的数据 2017-10-15
	*/
	private function auth($token){	
		if(!input('?get.timestamp') ||  !input('?get.nonce') || !input('?get.signature')){
			return false;
		}
		$data = array(input('get.timestamp'), input('get.nonce'), $token);
		$getsign = input('get.signature');
		sort($data, SORT_STRING);
		$signature = sha1(implode($data));

		return $signature === $getsign;
	}
}